//
//  LimitFreeCacheManager.m
//  LimitFree
//
//  Created by lijinghua on 16/3/3.
//  Copyright © 2016年 lijinghua. All rights reserved.
//

#import "LimitFreeCacheManager.h"
#import "NSString+Hashing.h"

@implementation LimitFreeCacheManager

+ (instancetype)sharedInstance{
    static LimitFreeCacheManager *s_manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_manager = [[LimitFreeCacheManager alloc]init];
    });
    return s_manager;
}

- (id)init{
    if (self = [super init]) {
        //创建缓存目录，放在沙盒目录的cache目录下
        //1.获取缓存目录
        //通过该函数，获取应用程序下的Cache目录，返回的是数组，对于ios
        //该数组中只有一个，所以返回第一个即可
        NSString * limitFreeCacheDir = [self limitFreeCacheDirectory];
        //2:创建目录
        [[NSFileManager defaultManager] createDirectoryAtPath:limitFreeCacheDir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return self;
}

- (NSString*)limitFreeCacheDirectory{
    NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *limitFreeCacheDir = [cacheDir stringByAppendingPathComponent:@"LimitFreeCache"];
    return limitFreeCacheDir;
}

//保存数据，该数据对应网络url的数据
//希望每一个url 对应的数据保存成一个文件，文件名可以使用url进行映射
- (void)saveData:(NSData*)data url:(NSString*)url{
    //生成文件名，并把数据写到文件中
    NSString *fileName = [url MD5Hash];
    NSString *fullPath = [[self limitFreeCacheDirectory] stringByAppendingPathComponent:fileName];
    //atomically：这个参数意思是如果为YES则保证文件的写入原子性,就是说会先创建一个临时文件,直到文件内容写入成功再导入到目标文件里.如果为NO,则直接写入目标文件里.
    [data writeToFile:fullPath atomically:YES];
}


//读取针对该url 保存的数据
- (NSData*)readData:(NSString*)url{
    //1:判断数据是否有效（存在&不过期）
    NSString *fileName = [url MD5Hash];
    NSString *fileFullPath = [[self limitFreeCacheDirectory] stringByAppendingPathComponent:fileName];
    if (![self isCacheValid:fileFullPath]) {
        return nil;
    }
    //2:有效的情况下读取
    NSData *data = [NSData dataWithContentsOfFile:fileFullPath];
    return data;
}

- (BOOL)isCachedUrlValidate:(NSString*)url
{
    NSString *fileName = [url MD5Hash];
    NSString *fullPath = [[self limitFreeCacheDirectory] stringByAppendingPathComponent:fileName];
    return [self isCacheValid:fullPath];
}

//判断缓存是否有效
- (BOOL)isCacheValid:(NSString*)fileFullPath{
    BOOL isFileExist = [[NSFileManager defaultManager] fileExistsAtPath:fileFullPath];
    if (isFileExist) {
        //是否过期
        //找到文件的最后修改时间和当前的时间做对比，如果超过一个小时，认为过期（缓存策略）
        NSDictionary *attrDic = [[NSFileManager defaultManager] attributesOfItemAtPath:fileFullPath error:nil];
        //取文件的最后修改时间
        NSDate *lastModify = attrDic.fileModificationDate;
        //找到时间间隔
        NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:lastModify];
        if(timeInterval < 60 * 60){
            return YES;
        }
    }
    
    //其他情况返回NO
    return NO;
}

@end
